﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace fap
{
    class 字符串操作

    {
        private static 字符串操作 _instance = null;
        public static 字符串操作 instance
        {
            get
            {

                if (null == _instance)
                {
                    _instance = new 字符串操作();
                }
                return _instance;
            }
            set
            {
                _instance = value;
            }

        }

        /// <summary>
        /// 计算字符串中子串出现的次数
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="substring">子串</param>
        /// <returns>出现的次数</returns>
        public int SubstringCount(string str, string substring)
        {
            if (str.Contains(substring))
            {
                string strReplaced = str.Replace(substring, "");
                return (str.Length - strReplaced.Length) / substring.Length;
            }

            return 0;
        }

        /// <summary>
        /// 计算特定字符串在某字符串中出现第N次位置
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="customChar">特定字符串</param>
        /// <param name="nIndex">特定字符串出现的第N次</param>
        /// <returns></returns>
        public int IndexOfCustomChar(string str, char customChar, int nIndex)
        {
            int num = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == customChar)
                {
                    num++;
                    if (num == nIndex)
                    {
                        return i;
                    }
                }
            }

            return -1;
        }    // 调用例子：    // 假如有一个字符串  string str = "1,2,3,4,5,6,7,8,9"; 那么    // 1.查找','在字符串中共出现了多少次 用 SubstringCount(str,",")即可    // 2.查找','在字符串中第5次出现的下标则用 IndexOfCustomChar(str,',',5)
    }
}
